#include "./../../../include/online/Reactor/Thread.h"
#include <iostream>
using std::cout;
using std::endl;

extern __thread const char *name;

Thread::Thread(ThreadCallback &&cb, const string &sname)
    : _thid(0), _isRunning(false), _name(sname), _cb(std::move(cb)) // 注册回调函数
{
}
Thread::~Thread()
{
}

void Thread::start()
{
    int ret = pthread_create(&_thid, nullptr, threadFunc, this);
    if (ret)
    {
        perror("pthread_create");
        return;
    }
    _isRunning = true;
}

void Thread::stop()
{
    if (_isRunning)
    {
        int ret = pthread_join(_thid, nullptr);
        if (ret)
        {
            perror("pthread_join");
            return;
        }
        _isRunning = false;
    }
}

void *Thread::threadFunc(void *arg)
{
    Thread *pth1 = static_cast<Thread *>(arg);
    name = pth1->_name.c_str();
    /* cout<<"线程号为"<<name<<endl; */
    if (pth1)
    {
        pth1->_cb(); // 如果启动起来没任务会卡在这一步
    }
    else
    {
        printf("pth==nullptr\n");
    }

    pthread_exit(nullptr);
}
